/*
 * @lc app=leetcode.cn id=331 lang=javascript
 *
 * [331] 验证二叉树的前序序列化
 */

// @lc code=start
/**
 * @param {string} preorder
 * @return {boolean}
 */
// var isValidSerialization = function(preorder) {
//   let stack = [];
//   preorder = preorder.split(',');
//   for (let i = 0; i<preorder.length; i++){
//     let value = preorder[i];
//     stack.push(value)
//     while(stack[stack.length-1] === "#" && stack[stack.length-2]==='#'){
//       stack.pop();
//       stack.pop();
//       stack[stack.length-1] = '#';
//     }
//   }

//   return stack.length === 1 && stack[0] === '#';
// };

/**
 * 复习 2021-08-04
 */
var isValidSerialization = function(preorder) {
  let preOrder = preorder.split(',');
  let stack = [];
  for (let i = 0; i < preOrder.length; i++) {
    let val = preOrder[i];
    stack.push(val);
    while(stack[stack.length - 1] === '#' && stack[stack.length - 2] === '#') {
      stack.pop();
      stack.pop();
      stack[stack.length-1] = '#';
    }
  }
  return stack.length === 1 && stack[0] === '#';
}
// @lc code=end

